package org.fengling.readingplatform.common.interceptor;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.fengling.readingplatform.model.entity.user.UserInfo;
import org.fengling.readingplatform.utils.AuthContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

public class UserLoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate ;


    //在请求之前
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        // 如果token不为空，那么此时验证token的合法性
        String token = request.getHeader("token");
        String userJSON = redisTemplate.opsForValue().get("user:readingplatform:" + token);

        // 放到threadlocal当中
        AuthContextUtil.setUserInfo(JSON.parseObject(userJSON, UserInfo.class));
        return true ;
    }
}
